﻿using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;


namespace Portal
{
    public static class SystemWebPage
    {
        public static void Json(this System.Web.UI.Page page, object o)
        {
            HttpContext.Current.Response.Buffer = true;

            HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddMilliseconds(0);
            HttpContext.Current.Response.Expires = 0;
            HttpContext.Current.Response.CacheControl = "no-cache";
            HttpContext.Current.Response.AppendHeader("Pragma", "No-Cache");
            HttpContext.Current.Response.Write(o.Serialization());
            HttpContext.Current.Response.End();
        }
    }
    public class BasePage : System.Web.UI.Page
    {

        /// <summary>
        /// 是否是AJAX请求
        /// </summary>
        public bool IsAjaxRequest
        {
            get
            {
                string sheader = HttpContext.Current.Request.Headers["X-Requested-With"];
                bool isAjaxRequest = (sheader != null && sheader == "XMLHttpRequest");
                return isAjaxRequest;
            }
        }
        /// <summary>
        /// 返回JSON数据
        /// </summary>
        /// <param name="o"></param>
        public void Json(object o)
        {
            HttpContext.Current.Response.Buffer = true;

            HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddMilliseconds(0);
            HttpContext.Current.Response.Expires = 0;
            HttpContext.Current.Response.CacheControl = "no-cache";
            HttpContext.Current.Response.AppendHeader("Pragma", "No-Cache");
            Response.Write(o.Serialization());
            Response.End();
        }
        /// <summary>
        /// 获取排序字段
        /// </summary>
        public string sort
        {
            get
            {
                var tem = HttpContext.Current.Request.QueryString["sort"] ?? HttpContext.Current.Request.Form["sort"];
                return string.IsNullOrEmpty(tem) ? "Sort" : tem;
            }
        }
        /// <summary>
        /// 获取排序方式
        /// </summary>
        public string order
        {
            get
            {
                var tem = HttpContext.Current.Request.QueryString["order"] ?? HttpContext.Current.Request.Form["order"];
                return string.IsNullOrEmpty(tem) ? "DESC" : tem;
            }
        }
        /// <summary>
        /// 当前页
        /// </summary>
        public int page
        {
            get
            {
                var tem = HttpContext.Current.Request.QueryString["page"] ?? HttpContext.Current.Request.Form["page"];
                return string.IsNullOrEmpty(tem) ? 1 : tem.ToInt();
            }
        }
        /// <summary>
        /// 每页数量
        /// </summary>
        public int rows
        {
            get
            {

                var tem = Fq("rows");
                return string.IsNullOrEmpty(tem) ? 15 : tem.ToInt();
            }
        }

        public string culture
        {
            get
            {
                var tem = HttpContext.Current.Request.QueryString["culture"] ?? HttpContext.Current.Request.Form["culture"];
                return string.IsNullOrEmpty(tem) ? "zh-cn" : tem;
            }
        }
        /// <summary>
        /// 获取KEY 提交过来数据（POST）
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string F(string key)
        {
            return (HttpContext.Current.Request.Form[key] ?? string.Empty).ToString(CultureInfo.InvariantCulture); ;
        }
        /// <summary>
        /// 获取KEY 提交过来数据（GET）
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string Q(string key)
        {
            return (HttpContext.Current.Request.QueryString[key] ?? string.Empty).ToString(CultureInfo.InvariantCulture); ;
        }
        /// <summary>
        /// 获取KEY 提交过来数据 （GET，POST）
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string Fq(string key)
        {
            return (HttpContext.Current.Request.Form[key] ?? HttpContext.Current.Request.QueryString[key] ?? string.Empty).ToString(CultureInfo.InvariantCulture);
        }
        public QueryModel BindModel(HttpContext controllerContext)
        {
            var model = new QueryModel();
            var dict = controllerContext.Request.Params;
            var keys = dict.AllKeys.Where(c => c.StartsWith("["));//我们认为只有[开头的为需要处理的
            var enumerable = keys as List<string> ?? keys.ToList();
            if (enumerable.Count() != 0)
            {
                foreach (var key in enumerable)
                {
                    if (!key.StartsWith("[")) continue;
                    var val = dict[key];
                    //处理无值的情况
                    if (string.IsNullOrEmpty(val)) continue;
                    AddSearchItem(model, key, val);
                }
            }
            return model;
        }

        /// <summary>
        /// 将一组key=value添加入QueryModel.Items
        /// </summary>
        /// <param name="model">QueryModel</param>
        /// <param name="key">当前项的HtmlName</param>
        /// <param name="val">当前项的值</param>
        public static void AddSearchItem(QueryModel model, string key, string val)
        {
            string field = "", prefix = "", orGroup = "", method = "";
            var keywords = key.Split(']', ')', '}');
            //将Html中的name分割为我们想要的几个部分
            foreach (var keyword in keywords)
            {
                if (Char.IsLetterOrDigit(keyword[0])) field = keyword;
                var last = keyword.Substring(1);
                if (keyword[0] == '(') prefix = last;
                if (keyword[0] == '[') method = last;
                if (keyword[0] == '{') orGroup = last;
            }
            if (string.IsNullOrEmpty(method)) return;
            if (!string.IsNullOrEmpty(field))
            {
                var item = new ConditionItem
                {
                    Field = field,
                    Value = val.Trim(),
                    Prefix = prefix,
                    OrGroup = orGroup,
                    Method = (QueryMethod)Enum.Parse(typeof(QueryMethod), method)
                };
                model.Items.Add(item);
            }
        }
        public QueryModel QueryModel { get { return BindModel(HttpContext.Current); } }
    }
    public class BaseUserControl : System.Web.UI.UserControl
    {




    }

}
